<template>
  <li
    @mouseenter="mouseHandler(true, $event)"
    @mouseleave="mouseHandler(false)"
    :style="{ backgroundColor: bgColor, color: myColor }"
  >
    <label>
      <input type="checkbox" v-model="isCompleted" />
      <span>{{ item.title }}</span>
    </label>
    <button class="btn btn-danger" v-show="isShow" @click="detele(item.id)">
      删除
    </button>
  </li>
</template>

<script lang="ts">
import { defineComponent, inject, ref, computed } from 'vue'
import { Todo } from '../types/todo'
export default defineComponent({
  name: 'Item',
  props: {
    item: {
      type: Object as () => Todo, //函数返回的是Todo类型
      default: () => {}
    }
  },
  setup(props) {
    const deleteTodo: any = inject('deleteTodo')
    const changeState: any = inject('changeState')
    // 背景颜色
    const bgColor = ref('white')
    // 字体颜色
    const myColor = ref('black')
    //是否显示删除按钮
    const isShow = ref(false)
    const mouseHandler = (type: boolean) => {
      if (type) {
        bgColor.value = 'pink'
        myColor.value = 'green'
        isShow.value = true
      } else {
        bgColor.value = 'white'
        myColor.value = 'black'
        isShow.value = false
      }
    }
    const detele = (id: number) => {
      if (window.confirm('确定要删除嘛?')) {
        deleteTodo(id)
      }
    }
    const isCompleted = computed({
      get() {
        return props.item.isCompleted
      },
      set(value) {
        changeState(props.item.id, value)
      }
    })
    // let activeLi = ref<any>(null)
    // let activeButton = ref<any>(null)
    // const mouseHandler = (type: boolean, e: MouseEvent) => {
    //   if (type) {
    //     activeLi = e.target
    //     activeLi.style.backgroundColor = 'pink'
    //     Array.from(activeLi.children).forEach((ele: any) => {
    //       if (ele.nodeName === 'BUTTON') {
    //         activeButton = ele
    //         activeButton.style.display = 'block'
    //       }
    //     })
    //   } else {
    //     activeLi.style.backgroundColor = ''
    //     activeButton.style.display = 'none'
    //   }
    // }
    return {
      mouseHandler,
      detele,
      bgColor,
      myColor,
      isShow,
      deleteTodo,
      isCompleted
    }
  }
})
</script>

<style scoped lang="scss">
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
</style>